package com.card.client.view;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.card.client.dialog.DeleteDialog;
import com.card.client.dialog.EditOutputAccountsDialog;
import com.card.client.entry.FinanceType;
import com.card.client.entry.OutputAccounts;
import com.card.client.entry.UserInfo;
import com.card.client.entry.Util;
import com.card.client.entry.ViewObject;
import com.card.client.service.FinanceTypeConfigService;
import com.card.client.service.FinanceTypeConfigServiceAsync;
import com.card.client.service.OutputAccountsService;
import com.card.client.service.OutputAccountsServiceAsync;
import com.card.client.service.UserInfoManageService;
import com.card.client.service.UserInfoManageServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.Cell;

public class OutputAccountsView extends Composite implements ViewObject {

	private static OutputAccountsViewUiBinder uiBinder = GWT.create(OutputAccountsViewUiBinder.class);

	interface OutputAccountsViewUiBinder extends UiBinder<Widget, OutputAccountsView> {
	}

	private final FinanceTypeConfigServiceAsync ftcs = GWT.create(FinanceTypeConfigService.class);
	
	private final OutputAccountsServiceAsync oas = GWT.create(OutputAccountsService.class);
	
	private final UserInfoManageServiceAsync uims = GWT.create(UserInfoManageService.class);
	
	private Grid grid = getGrid();
	
	@UiField HorizontalPanel table;
	
	@UiField Button addOutputAccounts;

	@UiField Label descript;
	
	@UiField HTML sum;
	
	private int total;
	
	private String[] title = OutputAccounts.title;
	
	private List<FinanceType> financeType = new ArrayList<FinanceType>();
	
	private UserInfo[] userInfoList;
	
	private OutputAccounts tempOutputAccounts;
	
	private boolean edit = false;
	
	private Long tempId;
	
	public OutputAccountsView() {
		initWidget(uiBinder.createAndBindUi(this));
		table.setWidth("100%");
		table.add(grid);
		grid.setWidth("100%");
		descript.setStyleName("descript");
		TableAction action = new TableAction();
		action.setOutputAccountsView(this);
		grid.addClickHandler(action);
		sum.setWidth("100%");
		sum.setStyleName("sum");
		uims.getAllUserInfo(new AsyncCallback<UserInfo[]>() {
			public void onSuccess(UserInfo[] result) {
				if(result!=null){
					userInfoList = result;
				} else {
					userInfoList = new UserInfo[0];
				}
			}
			public void onFailure(Throwable caught) {}
		});
	}

	public void onLoad(){
		ftcs.getAllFinanceType(new AsyncCallback<FinanceType[]>() {
			public void onSuccess(FinanceType[] result) {
				for(int i=0;i<result.length;i++){
					financeType.add(result[i]);
				}
			}
			public void onFailure(Throwable caught) {}
		});
		
		oas.getAllOutputAccounts(new AsyncCallback<OutputAccounts[]>() {
			public void onSuccess(OutputAccounts[] result) {
				if(result != null){
					total = 0;
					setData(result);
					sum.setText("支出合计：" + Util.intToStr(total) + " 元");
				}
			}
			public void onFailure(Throwable caught) {}
		});
	}
	
	private void setData(OutputAccounts[] result){
		if(result.length==0){
			grid.resize(1, title.length);
		} else {
			grid.resize(result.length + 1, title.length);
		}
		for(int i=0;i<title.length;i++){
			if(i==0){
				grid.getColumnFormatter().setWidth(i, "8%");
			} else if (i == 1){
				grid.getColumnFormatter().setWidth(i, "24%");
			} else {
				grid.getColumnFormatter().setWidth(i, "16%");
			}
		}
		for(int i=0;i<title.length;i++){
			grid.setText(0, i, title[i]);
			if(i!=(title.length-1)){
				grid.getCellFormatter().addStyleName(0, i, "header");
			} else {
				grid.getCellFormatter().addStyleName(0, i, "header-n");
			}
		}
		for(int i=0;i<result.length;i++){
			int a = 0;
			OutputAccounts ia = result[i];
			grid.setText(i+1, a++, Long.toString(ia.getId()));
			grid.setText(i+1, a++, ia.getExplain());
			grid.setText(i+1, a++, Util.intToStr(ia.getAccounts()) + "元");
			for(int b=0;b<financeType.size();b++){
				FinanceType ft = financeType.get(b);
				if(ia.getFinanceTypeId().equals(ft.getId())){
					grid.setText(i+1, a++, ft.getFinanceType());
					break;
				}
			}
			grid.setText(i+1, a++, DateTimeFormat(ia.getAppendTime()));
			for(int b=0;b<userInfoList.length;b++){
				UserInfo ui = userInfoList[b];
				if(ia.getUserId().equals(ui.getId())){
					grid.setText(i+1, a++, ui.getName());
				}
			}
			total = total + ia.getAccounts();
			reload(i+1);
		}
	}
	
	public Grid getGrid(){
		if(grid != null){
			return grid;
		}
		return new GreenMouseEventGrid();
	}
	
	private String DateTimeFormat(Date date){
		DateTimeFormat dateTimeFormat = DateTimeFormat.getFormat("yyyy-MM-dd");
		return dateTimeFormat.format(date);
	}
	
	@UiHandler("addOutputAccounts")
	void onClick(ClickEvent e) {
		EditOutputAccountsDialog eiad = new EditOutputAccountsDialog("添加支出记录", "添加一条支出记录", this, null, Util.DIALOG_CONTROL_ADD);
		eiad.show();
	}

	private void reload(int row) {
		descript.setText(null);
		if(row%2!=0){
			for(int i=0;i<title.length;i++){
				if(i==title.length-1){
					grid.getCellFormatter().setStyleName(row, i, "row0-n");
				} else {
					grid.getCellFormatter().setStyleName(row, i, "row0");
				}
			}
		} else {
			for(int i=0;i<title.length;i++){
				if(i==title.length-1){
					grid.getCellFormatter().setStyleName(row, i, "row1-n");
				} else {
					grid.getCellFormatter().setStyleName(row, i, "row1");
				}
			}
		}
	}
	
	class GreenMouseEventGrid extends MouseEventGrid {

		public void onMouseOut(Element td, int row) {
			reload(row);
		}

		public void onMouseOver(Element td, int row) {
			Element tr = DOM.getParent(td);
			int column = DOM.getChildIndex(tr, td);
			String name = grid.getHTML(row, 1);
			if(column == 0){
				descript.setText("删除支出记录 “" + name + "” ");
			} else {
				descript.setText("修改支出记录 “" + name + "” 信息");
			}
			for(int i=0;i<title.length;i++){
				if(i==title.length-1){
					grid.getCellFormatter().setStyleName(row, i, "rows-n");
				} else {
					grid.getCellFormatter().setStyleName(row, i, "rows");
				}
			}
		}
		
	}
	
	EditOutputAccountsDialog eiad = null;
	
	public class TableAction implements ClickHandler {
		
		private OutputAccountsView outputAccountsView;
		
		public void onClick(ClickEvent event) {
			HTMLTable table = (HTMLTable)event.getSource();
			Cell Mycell = table.getCellForEvent(event);
			if( Mycell == null ) return;
			int row = Mycell.getRowIndex();
			int col = Mycell.getCellIndex();
			reload(row);
			String tid = grid.getHTML(row, 0);
			tempId = Long.valueOf(tid);
			getObject();
			Long id = Long.valueOf(grid.getHTML(row, 0));
			if(col == 0){
				String des = "确认删除支出记录 “" + grid.getHTML(row, 1) + "” 么？";
				DeleteDialog dd = new DeleteDialog("记录", des, outputAccountsView, id);
				dd.show();
			} else {
				if(!edit){
					edit = true;
				}
				String des = "修改支出记录 “" + grid.getHTML(row, 1) + "” 的信息";
				eiad = new EditOutputAccountsDialog("修改支出记录", des, outputAccountsView, tempOutputAccounts, Util.DIALOG_CONTROL_EDIT);
				eiad.show();
			}
		}

		public void setOutputAccountsView(OutputAccountsView outputAccountsView){
			this.outputAccountsView = outputAccountsView;
		}
	}
	
	public void delDate(Long id) {
		if(id == null){
			return;
		}
		oas.delOutputAccounts(id, new AsyncCallback<Void>() {
			public void onSuccess(Void result) {
				onLoad();
			}
			public void onFailure(Throwable caught) {}
		});
	}

	public void refresh() {
		onLoad();
	}
	
	private void getObject(){
		oas.getAllOutputAccounts(new AsyncCallback<OutputAccounts[]>() {
			public void onSuccess(OutputAccounts[] result) {
				for(int i=0;i<result.length;i++){
					if(result[i].getId().equals(tempId)){
						tempOutputAccounts = result[i];
						if(edit){
							edit = false;
							eiad.setOutputAccounts(tempOutputAccounts);
						}
						break;
					}
				}
			}
			public void onFailure(Throwable caught) {}
		});
	}
}
